//
//  Ext+Number.swift
//  MasterBoard-Swift
//
//  Created by JunMing on 2022/10/12.
//  
//

import UIKit

extension Double {
    /// date
    public var date: Date {
        return Date(timeIntervalSince1970: self)
    }
    
    public func dateFormat(_ format: String = "yyyy-MM-dd HH:mm:ss") -> String {
        let date = Date(timeIntervalSince1970: self)
        let dfmatter = DateFormatter()
        dfmatter.dateFormat = format
        return dfmatter.string(from: date)
    }
}

public extension Int {
    // 返回指定格式的字符串
    func string(format: String? = nil) -> String {
        if let format = format {
            return String(format: format, self)
        } else {
            return "\(self)"
        }
    }
    
    // random number from min to max
    static func random(min: Int = 0, max: Int) -> Int {
        let random = Int(arc4random())
        let number = random % (max + 1 - min) + min
        return number
    }
    
    /// 返回当前值是否是偶数
    var isEven: Bool {
        return self % 2 == 0
    }
    
    static var uid: Int {
        let x1 = Int.random(min: 0, max: 100000)
        let x2 = Int.random(min: 0, max: 100000)
        let x3 = Int.random(min: 0, max: 100000)
        return x1 + x2 + x3
    }
    
    var formatTime: String {
        let minutes = self / 60
        let seconds = self % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }
    
    /// 随机6-10位的字符串，数字和字母组合
    static var random: String {
        // 定义所有可能的字符：字母(大小写)和数字
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        // 随机生成6到10之间的长度
        let length = Int.random(in: 6...10)
        
        var result = ""
        // 生成指定长度的随机字符串
        for _ in 0..<length {
            // 从字符集中随机选择一个字符
            let randomIndex = Int.random(in: 0..<letters.count)
            let character = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
            result.append(character)
        }
        
        return result
    }
}
